<template>
  <div class="main">
    <div class="content">
      <div class="main-top">
        <div class="banner">
          <!--          <img style="width: 560px; margin:0 ;padding: 0"-->
          <!--               src="../assets/images/yl02.jpg" alt=""/>-->
        </div>


        <div class="login-form-sty">

          <h1 style="right: 0;left: 0;top: 20rem;">顶呱呱电玩管理系统</h1>
<!--          <div style="display: flex; justify-content: space-between;margin-top: 15px; height:50px">-->

<!--              <div style="display: flex; align-items: center ; flex-direction: column;">-->
<!--                <span  :class="this.activeMethod==='accountsLogin'?'msg_title activeSty':'msg_title notActive'"  @click="changeForm('accountsLogin')">账号登录</span>-->
<!--                <div  class="sub_form_title" v-show="this.activeMethod==='accountsLogin'"></div>-->
<!--              </div>-->

<!--              <div style="display: flex; align-items: center ; flex-direction: column;">-->
<!--                <span :class="this.activeMethod==='ddLogin'?'msg_title notActive':'msg_title activeSty'" @click="changeForm('ddLogin')">钉钉登录</span>-->
<!--                <div class="sub_form_title" v-show="this.activeMethod==='ddLogin'"></div>-->
<!--              </div>-->
<!--          </div>-->

          <el-form ref="loginForm"  v-loading="loading" v-if="this.activeMethod==='accountsLogin'" :model="loginForm"  :rules="loginRules" class="form" label-width="0">
            <!-- 用户id -->
            <el-form-item prop="username" class="form-group">
              <el-input v-model="loginForm.username" prefix-icon="iconfont icon-yonghu" class="in">
                <svg-icon
                  slot="prefix"
                  icon-class="user"
                  class="el-input__icon input-icon"
                />
              </el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item  prop="password" class="form-group">
              <el-input v-model="loginForm.password" prefix-icon="iconfont icon-mima"
                        @keyup.enter.native="handleLogin"
                        show-password class="in">
                <svg-icon
                  slot="prefix"
                  icon-class="password"
                  class="el-input__icon input-icon"
                />
              </el-input>
            </el-form-item>

            <el-form-item prop="isLock">
              <slider-verify-code v-if="this.captchaOnOff" v-model="loginForm.isLock" @change="handlerLock"></slider-verify-code>
            </el-form-item>
          </el-form>


          <el-form ref="loginForm" v-loading="loading" v-if="this.activeMethod==='ddLogin'"  label-width="0">
            <div  id="login_container" class="dd-form-group"></div>
          </el-form>

          <button v-if="this.activeMethod==='accountsLogin'" :class="'btnEnabled'" @click="handleLogin">登录</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import SliderVerifyCode from "@/components/Code/slider-verify-code";
import Cookies from "js-cookie";
import {encrypt, decrypt} from '@/utils/jsencrypt'

export default {
  components: {SliderVerifyCode},
  name: "Login",
  data() {
    return {
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        isLock: true,
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      //登录方式
      activeMethod: 'accountsLogin',
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
      //二维码弹窗开关
      scanCodeVisible: false,
      //登录页面loading
      loginLoading: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    },
  },
  mounted() {
    const {code} = this.$route.query
    if (code) {
      this.loginLoading = true
      this.handleDingLogin(code)
    }

  },
  created() {
    this.getCookie();
  },
  methods: {
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },

    /** 切换登录方式*/
    changeForm(formName) {
      this.activeMethod = formName;

      //钉钉登录
      if (this.activeMethod === "ddLogin") {
        this.clickScanCode(true)
      }
    },

    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (this.captchaOnOff && !this.loginForm.isLock) {
          this.$message.error("请滑动滑块验证")
        } else {
          if (valid) {
            this.loading = true;
            if (this.loginForm.isLock) {
              Cookies.set("username", this.loginForm.username, {expires: 30});
              Cookies.set("password", encrypt(this.loginForm.password), {expires: 30});
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
            }
            this.$store.dispatch("Login", this.loginForm).then(() => {
              this.$router.push({path: this.redirect || "/"}).catch(() => {
              });
            }).catch(() => {
              this.loading = false;

              this.loginForm.isLock = false
            });
          }
        }
      });
    },
    dingInit() {
      let appid = process.env.VUE_APP_DING_APP_KEY
      var url = encodeURIComponent(process.env.VUE_APP_BASE_URL + '/login');
      var goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' + appid + '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + url)

      this.$nextTick(() => {
        var obj = DDLogin({
          id: "login_container",
          goto: goto,
          style: "border:none;background-color:#FFFFFF;",
          width: "300", // 二维码的宽度
          height: "300" // 二维码的高度
        })


        this.loading = false;
      })

      var handleMessage = function (event) {
        var origin = event.origin;

        if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
          var loginTmpCode = event.data;
          // console.log("loginTmpCode", loginTmpCode);
          //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
          window.location.href = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=" + appid + "&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=" + url + "&loginTmpCode=" + loginTmpCode;
        }
      };
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
      }
    },
    handleDingLogin(code) {
      console.log(code)
      //此处根据自己需求使用code
      this.$store.dispatch("DingLogin", code).then(() => {
        this.$router.push({path: this.redirect || "/"}).catch(() => {
        });
      }).catch(() => {
        this.loading = false;
      });
    },

    handlerLock(data) {
      if (data) {
        this.$refs.loginForm.validateField('isLock');
      }
    },


    clickScanCode(flag) {
      this.loading = true;
      this.scanCodeVisible = flag
      if (flag) {
        setTimeout(this.dingInit, 200)
      } else {
      }
    }


  }
};


</script>

<style>
.nav span {
  width: 80px;
  font-size: 16px;
  height: 60px;
  padding-bottom: 12px;
  margin-right: 10px;

}

.nav span:hover {
  color: #007AFF;
  border-bottom: 2px solid #007AFF;
  border-bottom-width: 4px;
}

.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: url("../assets/images/login.png");
  justify-content: center;
  text-align: center;
}

.content {
  width: 1000px;
}

.banner img {
  width: 560px;
  border-bottom-left-radius: 8px;
  border-top-left-radius: 8px;
}


.main-top {
  display: inline-flex;
  border-radius: 8px;
}

.login-form-sty {
  width: 440px;
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
}


.btnEnabled {
  width: 320px;
  height: 46px;
  font-size: 16px;
  background-color: #007AFF;
  border-style: none;
  outline: none;
  color: #fff;
  border-radius: 30px;
  margin-bottom: 30px;

}

.login-form .btnEnabled:hover {
  background-color: #006EE7;
  cursor: pointer;

}


.sub_form_title {
  background-color: #007AFF;
  width: 32px;
  height: 5px;
  border-radius: 4px;
  margin-top: 10px;
}

.activeSty {
  font-size: 18px;
  width: 150px;
}


.notActive {
  font-size: 18px;
  width: 150px;
}

.msg_title:hover {
  cursor: pointer;
}

.form {
  display: flex;
  flex-direction: column;
}

.dd-form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 35px;
  margin-top: -35px;
  height: 330px;
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 30px;
  height: 50px;
}
</style>
